package com.lujianfei.share.shareSingle;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Parcelable;
import android.text.TextUtils;
import android.widget.Toast;

import com.lujianfei.share.ShareContext;
import com.lujianfei.share.shareBase.SharePlatforms;
import com.lujianfei.share.shareBase.ShareBase;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.core.content.FileProvider;

public class ShareSingle implements ShareBase {

    private Context context;
    private String title;
    private String content;
    private String dialogTitle;
    private Set<String> activiyNames;
    private String path;

    public ShareSingle(Context context) {
        this.context = context;
        this.activiyNames = new HashSet<>();
    }

    @Override
    public ShareBase share(String title, String content, String dialogTitle) {
        this.title = title;
        this.content = content;
        this.dialogTitle = dialogTitle;
        return this;
    }

    @Override
    public ShareBase image(String[] paths) {
        if (null != paths) {
            path = paths[0];
        }
        return this;
    }

    @Override
    public ShareBase withPlatforms(List<SharePlatforms> platforms) {
        if (null != platforms) {
            for (SharePlatforms platform :
                    platforms) {
                activiyNames.add(platform.getType());
            }
        }
        return this;
    }

    @Override
    public void show() {
        Set<String> packages = new HashSet<>();
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        // 查询所有可以分享的Activity
        List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (!resInfo.isEmpty()) {
            List<Intent> targetedShareIntents = new ArrayList<>();
            Uri uri = null;
            for (ResolveInfo info : resInfo) {
                Intent targeted = new Intent(Intent.ACTION_SEND);
                targeted.setType("text/plain");
                ActivityInfo activityInfo = info.activityInfo;
                if (!TextUtils.isEmpty(content)) {
                    // 分享出去的内容
                    targeted.putExtra(Intent.EXTRA_TEXT, content);
                }
                if (!TextUtils.isEmpty(title)) {
                    // 分享出去的标题
                    targeted.putExtra(Intent.EXTRA_SUBJECT, title);
                }
                // 分享图片
                if (!TextUtils.isEmpty(path)) {
                    if (null==uri) {
                        File file = new File(path);
                        uri = FileProvider.getUriForFile(context, ShareContext.authorities, file);
                    }
                    targeted.putExtra(Intent.EXTRA_STREAM, uri);
                    targeted.setType("image/jpeg");
                    targeted.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                packages.add(activityInfo.packageName);
                targeted.setPackage(activityInfo.packageName);
                targeted.setClassName(activityInfo.packageName, info.activityInfo.name);
                if (activiyNames.contains(activityInfo.name)) {
                    targetedShareIntents.add(targeted);
                }
            }
            if (packages.contains("com.tencent.mm") && activiyNames.contains(SharePlatforms.ShareTypeWechatMoment.getType())) {
                try {
                    targetedShareIntents.add(shareWechatMoment(path, content));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (TextUtils.isEmpty(dialogTitle)) {
                dialogTitle = "分享至";
            }
            // 选择分享时的标题
            Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), dialogTitle);
            if (chooserIntent == null) {
                return;
            }
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
            try {
                context.startActivity(chooserIntent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(context, "找不到该分享应用组件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 拉起微信朋友圈发送单张图片
     */
    private Intent shareWechatMoment(String path, String content) throws Exception {
        Uri uriToImage = Uri.fromFile(new File(path));
        Intent shareIntent = new Intent();
        //发送图片到朋友圈
        ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        //发送图片给好友。
        shareIntent.setComponent(comp);
        shareIntent.putExtra("Kdescription", content);
        shareIntent.setAction(Intent.ACTION_SEND);
        if (TextUtils.isEmpty(path)) {
            shareIntent.setType("text/plain");
        } else {
            shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
            shareIntent.setType("image/jpeg");
        }

        return shareIntent;
    }
}
